package com.wechat.pay.contrib.apache.httpclient.util;

import org.apache.commons.codec.binary.Base64;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.security.*;

public class PaySignUtil {
    /**
     * @param priKeyPath apiclient_key.pem 路径
     * @param appid      公众号Id
     * @param timestamp  时间戳
     * @param nonceStr   随机字符
     * @param prepay_id  【预支付交易会话标识】 预支付交易会话标识。用于后续接口调用中使用，该值有效期为2小时
     * @return
     */
    public static String getPaySign(String priKeyPath, String appid, String timestamp, String nonceStr, String prepay_id) throws FileNotFoundException, SignatureException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        String source = appid + "\n";
        source += timestamp + "\n";
        source += nonceStr + "\n";
        source += "prepay_id=" + prepay_id + "\n";
        String paySign = signBySHA256WithRSA(priKeyPath, source);
        return paySign;
    }

    /**
     * @param priKeyPath apiclient_key.pem 路径
     * @param source
     * @return
     * @throws InvalidKeyException
     * @throws FileNotFoundException
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws SignatureException
     */
    public static String signBySHA256WithRSA(String priKeyPath, String source) throws InvalidKeyException, FileNotFoundException, NoSuchAlgorithmException, UnsupportedEncodingException, SignatureException {
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new FileInputStream(priKeyPath));
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(merchantPrivateKey);
        signature.update(source.getBytes("UTF-8"));
        return Base64.encodeBase64String(signature.sign());

    }

}
